const request = require('./request.js');

module.exports = function(options) {
    let {
        rid,
        paypart,
        paynum
    } = options;
    let access_token = wx.getStorageSync('access_token');

    return new Promise((resolve, reject) => {
        request.post('c=pay&a=createjs', {
            rid,
            paynum,
            paypart,
            access_token
        }).then(res => {
            console.log(res);
            let pid = res.pid;
            wx.requestPayment({
                timeStamp: res.timeStamp,
                nonceStr: res.nonceStr,
                package: res.package,
                signType: 'MD5',
                paySign: res.paySign,
                success(res) {
                    let timer = null;
                    // console.log('pay-suc-cb', res)
                    timer = setInterval(() => {
                        request.post('c=pay&a=ordercheck', {
                            pid: pid,
                            access_token
                        }).then(res => {
                            console.log(res);
                            if (res.paystatus == 'finish') {
                                resolve();
                                clearInterval(timer);
                            } else if (res.paystatus == 'error') {
                                reject();
                                clearInterval(timer);
                            }
                        });
                    }, 1000);
                },
                fail(res) {
                    console.log('pay-fail-cb', res);
                    request.post('c=pay&a=faildone', {
                        rid,
                        paynum,
                        paypart,
                        access_token
                    }).then(res => {
                        console.log('faildone', res);
                        reject();
                    }).catch(err => {
                        console.log(err);
                    });
                }
            });
        }).catch(err => {
            console.log(err);
            wx.showToast({
                title: err.msg,
                icon: 'none'
            });
        });
    });
};